package com.nvwa.mvp.mybatis.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nvwa.coding.util.safe.Coding;
import com.nvwa.dto.query.PageQuery;
import com.nvwa.mvp.mybatis.mapper.UserMapper;
import com.nvwa.mvp.mybatis.model.UserModel;
import com.nvwa.mvp.mybatis.po.User;
import com.nvwa.pagehelper.PageInfoBuilder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User getUser() {
        User u = userMapper.selectById(1);
        return u;
    }

    public PageInfo<UserModel> pageUser(PageQuery query) {
        Page<User> page = PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<User> list = userMapper.selectList();
        List<UserModel> models = Coding.stream(list).map(this::convertToModel).collect(Collectors.toList());
        return PageInfoBuilder.newBuilder(page, models).build();
    }

    private UserModel convertToModel(User user) {
        UserModel model = new UserModel();
        model.setName(user.getUserName());
        model.setPwd(user.getPassword());
        return model;
    }
}